package io.seata.gatewayservice.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.seata.gatewayservice.tool.JwtUtil;
import io.seata.gatewayservice.tool.ResponseResult;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : author
 * @create 2022/8/24 18:58
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("LoginFilter：进入");
        //特殊路径放行，不需要拦截  /auth/login
        ServerHttpRequest request = exchange.getRequest();
        if (request.getURI().getPath().contains("/auth/login")) {
            System.out.println("LoginFilter：请求登录，直接放行");
            return chain.filter(exchange);
        }
        System.out.println("LoginFilter：其它请求验证token");
        //请求其它页面，请求头应该携带token
        String token = request.getHeaders().getFirst("token");

        String username = JwtUtil.getUname(token);
        String user_se = null;
        String right_se = null;
        if (username.equals("a")) {
            user_se = "student-find";
        }
        if (request.getURI().getPath().equals("/student/1")) {
            right_se = "student-find";
        }

        if (!StringUtils.isEmpty(token) && JwtUtil.verify(token)) {
            System.out.println("LoginFilter：token有效，放行");
            if (user_se.equals(right_se)) {
                System.out.println("LoginFilter：token有效，权限有效，放行");
                return chain.filter(exchange);
            }

        }
        System.out.println("LoginFilter：token无效或权限无效，拦截");
        return write(exchange);
    }

    public Mono<Void> write(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        ResponseResult<String> responseResult = new ResponseResult<>(401, "login first", "先登录");
        try {
            byte[] bytes = new ObjectMapper().writeValueAsString(responseResult)
                    .getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            //响应体JSON，设置中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

